<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/2
 * Time: 8:41
 */

namespace common\rest\actions\myorder;

use common\models\c2\statics\SalesOrderStateType;
use Yii;
use yii\base\Model;
use yii\rest\Action;
use common\rest\statics\ResponseDatum;
use common\rest\statics\OperationResult;

class DetailAction extends Action
{
    /**
     * @var string the scenario to be assigned to the new model before it is validated and saved.
     */
    public $scenario = Model::SCENARIO_DEFAULT;

    /**
     * @var string the name of the view action. This property is need to create the URL when the model is successfully created.
     */
    public $viewAction = 'view';

    /**
     * auth id
     * @var string
     */
    public $authIdAttribute = "user_id";

    public function run($id){
        $modelClass = $this->modelClass;
        $model = $modelClass::findOne(['id' => $id]);
        $data = [];
        if($model->customer_id != Yii::$app->user->id){
            return ResponseDatum::getErrorDatum(['code' => OperationResult::ERROR_404],[]);
        }
        if(!empty($model)){
            $group = \common\models\c2\entity\CustomerConsumeGroup::find()->where(['sales_order_id' => $id])->one();
            if (!empty($group)) {
//                 $groupId = $group->id;
                $group_users = $group->customerConsumeGroupUser;
                $currently_group_member_number = count($group_users);
                $group_team_number = $group->users_count;
                $group_state = $model->group_state;
                $group_state_label = \common\models\c2\statics\CustomerConsumeGroupState::getLabel($group->state);
                $group = 1;
            } else {
                $group = 0;
                $group_state = 0;
                $currently_group_member_number = 0;
                $group_state_label = '';
                $group_team_number = 0;
            }
            $bargain = $model->customerConsumeGroup;
            $data = [
                'id'=>$model->id,
                'code'=>$model->code,
                'is_group' => $group,
                'group_state' => $group_state,
                'group_state_label' => $group_state_label,
                'group_team_number' => $group_team_number,
                'bargain_url' => $bargain ? ESHOP_BASE_URL.'/activity/bargain?id='.$bargain->id : '',
                'currently_group_member_number' => $currently_group_member_number,
                'install_price' => $model->install_price?$model->install_price:0,
                'state_label'=>SalesOrderStateType::getLabel($model->state),
                'state'=>$model->state,
                'created_at'=>$model->created_at,
                'sub_total'=>$model->sub_total,
                'discounted_total'=>$model->discounted_total,
                'grand_total'=>$model->grand_total,
                'invoice_type' => $model->invoice?$model->invoice->is_vat:'',
                'invoice_label'=>!empty($model->invoice)?$model->invoice->title:'暂无发票',
                'comment_state'=>$model->comment_state,
//                'kz'=>$model->getSnapshot($model->state)
                'snapshot'=>$model->getSnapshot(),
                'enable_group'=>$model->getIsActivityEndding()?1:0,
            ];
        }

        $salesOrderPayment = $model->salesOrderPayment;
        if(!empty($salesOrderPayment)){
            $data = \yii\helpers\ArrayHelper::merge($data,[
                'payment_label'=>!empty($salesOrderPayment->paymentMethod)?$salesOrderPayment->paymentMethod->label:'',
            ]);
        }

        $salesOrderAddress = $model->getSalesAddressModel()->one();
        if(!empty($salesOrderAddress)){
            $data = \yii\helpers\ArrayHelper::merge($data,[
                'user_name'=>$salesOrderAddress->first_name.$salesOrderAddress->last_name,
                'phone'=>$salesOrderAddress->phone,
                'address'=>$salesOrderAddress->regionLabel(),
            ]);
        }

        $salesOrderItems = $model->getSalesItems()->all();
        $sales_order_items = [];
        if(!empty($salesOrderItems)){
            foreach($salesOrderItems as $item => $salesOrderItem){
                if(!empty($salesOrderItem)){
                    if (\common\helpers\RefundStateHelper::enbaleRefundQuantity($salesOrderItem->id) != 0) {
                       $state = \common\models\c2\statics\SalesOrderItemStateType::TYPE_APPLY;
                   } else if((\common\helpers\RefundStateHelper::getRefundState($salesOrderItem->id) == \common\models\c2\statics\RefundOrderStateType::TYPE_FINISH) && \common\helpers\RefundStateHelper::enbaleRefundQuantity($salesOrderItem->id) == 0) {
                       $state = \common\models\c2\statics\SalesOrderItemStateType::TYPE_FINISHED;
                   } else {
                       $state = \common\models\c2\statics\SalesOrderItemStateType::TYPE_APPLYING;
                   }
                    $state_label = \common\models\c2\statics\SalesOrderItemStateType::getLabel($state);

                    $product = !empty($salesOrderItem->getOrderProduct())?$salesOrderItem->getOrderProduct():$salesOrderItem->product;
                    $productLogo = !empty($salesOrderItem->getOrderProduct())?$salesOrderItem->getOrderProduct()['s_logo']:$salesOrderItem->product->mediumUrl;
                    $productSku = !empty($salesOrderItem->getOrderProductSku())?$salesOrderItem->getOrderProductSku()['label']:$salesOrderItem->sku_label;
                    $sales_order_items[$item] = [
                        'order_item_id'=>$salesOrderItem->id,
                        'product_id' => $salesOrderItem->product_id,
                        'product_sku_id' => $salesOrderItem->product_sku_id,
                        'product_name'=>$product->label,
                        'sku_label'=>$productSku,
                        'quantity'=>$salesOrderItem->quantity,
                        'market_price'=>$salesOrderItem->market_price,
                        'discount_price'=>$salesOrderItem->discount_price,
                        'sale_price'=>$salesOrderItem->sale_price,
                        'state'=>$state,
                        'state_label' => $state_label,
                        'refund_order_item_id'=>$salesOrderItem->refund_order_item_id,
                        'product_images'=>[
                            'icon'=>$productLogo,
                            'medium'=>$productLogo,
                            'original'=>$productLogo,
                        ]
                    ];
                    $refund_order_count = 0;
                    if(!empty($salesOrderItem->refundItem)){
                        foreach($salesOrderItem->refundItem as $refundItem){
                            $refund_order_count += $refundItem->quantity;
                        }
                    }
                    $sales_order_items[$item] =  \yii\helpers\ArrayHelper::merge($sales_order_items[$item],[
                        'refund_order_count'=>$refund_order_count,
                    ]);
                }
            }
            $data = \yii\helpers\ArrayHelper::merge($data,[
                'sales_order_items'=>$sales_order_items,
            ]);
        }
        if ($model) {
            return ResponseDatum::getSuccessDatum(['message' => Yii::t('app.c2', 'Operation completed successfully!')], $data);
        } else {
            return ResponseDatum::getErrorDatum(['code' => OperationResult::ERROR_404], []);
        }
    }

}